package com.jhws.core.spring.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.jhws.common.Page;
import com.jhws.common.PageRoll;
import com.jhws.core.spring.PageContext;

/**
 * 分页拦截
 *
 * @author xiaokek
 * @since 2015年12月27日 上午10:31:35
 */
public class PageInterceptor extends HandlerInterceptorAdapter{
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		int pageSize = NumberUtils.toInt(request.getParameter("pageSize"), 10) ;
		if(pageSize > 0){
			int currPage = NumberUtils.toInt(request.getParameter("page"), 0) ;
			if(currPage > 0){
				int beginIndex = pageSize * (currPage - 1);
				Page page = new Page(beginIndex,pageSize,null);
				PageContext.setPage(page);
				
			}
		}
		
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		Page page = PageContext.getPage(false);
		if(page != null && page.getList() != null){
			PageRoll pr = new PageRoll(request, page.getNumberPerPage(), page.getCurrentPageSequence(),page.getTotalNumber());
			request.setAttribute("pr", pr.Show(true, true, true, true));
		}
	}
	
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		PageContext.removePage();
	}
}
